from __future__ import annotations

import os
from pathlib import Path


APP_NAME = "agent-workspace"


def get_home() -> Path:
    """Return the workspace home directory (creates it if missing).

    Order of precedence:
    - AW_HOME
    - ~/.agent-workspace
    """
    env = os.getenv("AW_HOME")
    home = Path(env).expanduser() if env else Path.home() / f".{APP_NAME}"
    home.mkdir(parents=True, exist_ok=True)
    (home / "logs").mkdir(parents=True, exist_ok=True)
    (home / "attachments").mkdir(parents=True, exist_ok=True)
    (home / "export").mkdir(parents=True, exist_ok=True)
    return home


def get_memory_dir() -> Path:
    """Return the memU memory directory used by this app.

    Order of precedence:
    - AW_MEMORY_DIR
    - <home>/memory
    """
    env = os.getenv("AW_MEMORY_DIR")
    if env:
        p = Path(env).expanduser()
    else:
        p = get_home() / "memory"
    p.mkdir(parents=True, exist_ok=True)
    # Ensure embeddings dir exists; memU expects it
    (p / "embeddings").mkdir(parents=True, exist_ok=True)
    return p


def get_config_dir() -> Path:
    xdg = os.getenv("XDG_CONFIG_HOME")
    cfg = Path(xdg).expanduser() if xdg else Path.home() / ".config"
    root = cfg / APP_NAME
    root.mkdir(parents=True, exist_ok=True)
    return root


def get_accounts_path() -> Path:
    return get_config_dir() / "accounts.json"


def get_log_path() -> Path:
    return get_home() / "logs" / "aw.log"


def get_attachments_dir_for(event_id: str) -> Path:
    d = get_home() / "attachments" / event_id
    d.mkdir(parents=True, exist_ok=True)
    return d
